package org.yx.service.sbas.save_product;

import java.util.ArrayList;
import java.util.List;

import org.dbist.dml.Query;
import org.yx.exception.BizException;
import org.yx.models.SbasMatPth;
import org.yx.models.SbasProdMat;
import org.yx.utils.BaseService;
import org.yx.utils.FieldMap;

import com.xiaoleilu.hutool.util.StrUtil;

/**
 * 新增或修改产品信息
 * 
 * @author zxw
 * @since 2018/03/25
 **/
public class SbasSaveProductService extends BaseService {
	public SbasSaveProductOut saveProduct(SbasSaveProductIn in) throws Exception {
		checkStringNotBlank(in, "matCode,matVer");

		SbasProdMat oldMat = selectWithPk(SbasProdMat.class, in.getUserToken().getOrgCode(), in.getMatCode(),
				in.getMatVer());
		SbasProdMat mat = new SbasProdMat();
		if (oldMat != null) {
			copyProperties(oldMat, mat);
		}
		copyProperties(in, mat);
		mat.setOrgCode(in.getUserOrgCode());
		mat.setMatStatus('N');

		if (oldMat != null) {
			update(mat);
		} else {
			mat.setQcHoldFlag('N');
			insert(mat);
		}

		if (in.getPathList() != null && in.getPathList().size() > 0) {
			Query query = new Query();
			query.addFilter("nowDate", getCurrentTime());
			query.addFilter("userId", in.getUserToken().getUserId());
			query.addFilter("orgCode", mat.getOrgCode());
			query.addFilter("matCode", mat.getMatCode());
			query.addFilter("matVer", mat.getMatVer());
			executeBySqlPath("update_product_path_to_delete.sql", query);

			List<SbasMatPth> pthList = new ArrayList<SbasMatPth>();
			for (int i = 0; i < in.getPathList().size(); i++) {
				SbasMatPth pth = in.getPathList().get(i);
				if (StrUtil.isBlank(pth.getPathCode())) {
					throw new BizException("SYS-0004", new FieldMap("parameter", "pathList.pathCode"));
				}

				pth.setOrgCode(mat.getOrgCode());
				pth.setMatCode(mat.getMatCode());
				pth.setMatVer(mat.getMatVer());
				pth.setPathCode(pth.getPathCode());
				pth.setSeqNum(i);
				pth.setPathStatus('N');

				pthList.add(pth);
			}

			upsertBatch(pthList);
		}

		SbasSaveProductOut out = new SbasSaveProductOut();

		return out;
	}
}